package com.demos.cqp.dnt.mvc.controller;

import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.struts2.interceptor.SessionAware;

import com.demos.cqp.dnt.dao.DAOException;
import com.demos.cqp.dnt.dao.UtilisateurDAO;
import com.demos.cqp.dnt.domain.Utilisateur;
import com.opensymphony.xwork2.ActionSupport;

public class ConnexionAction extends ActionSupport implements SessionAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7726702184864195796L;

	@Inject
	@Named("userDAO")
	private UtilisateurDAO dao;

	private String login;
	private String password;

	private Map<String, Object> session;

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	@Override
	public String execute() {
		System.out.println("####### COnnexion en tant que " + login);

		Utilisateur user = null;
		try {
			user = validateLogin(login, password);

		} catch (DAOException e) {
			e.printStackTrace();
			getActionErrors().add(e.getMessage());
		}
		
		if (user == null) {
			return "error";
		} else {
			session.put("user", user);
			return "success";
		}

	}

	/**
	 * Validate the entered data
	 * 
	 * If there is no valid data, the method will return null
	 * 
	 * @param login
	 *            given at the jsp
	 * @param password
	 *            given at the jsp
	 * @return a user if one was found and validated
	 */
	private Utilisateur validateLogin(String login, String password)
			throws DAOException {
		// All parameters must be valid
		if (login == null || password == null) {
			return null;
		}

		// Get a user by key
		Utilisateur user = dao.consulter(login);
		System.out.println("########## " + user);
		System.out.println("########## " + login + " ###### " + password);
		if (user == null) {
			return null;
		}

		// Check if the password is valid
		if (!user.getPassword().equals(password.trim())) {
			return null;
		}

		return user;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;

	}
}